package com.midcent.networklib.interfac;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonRequest;
import com.midcent.networklib.manager.HttpRequestNetManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;

/**
 * 根据接口要求重写请求基类
 * 提供请求签名相关算法
 */
public class HttpJObjectRequest extends JsonRequest {

    protected String timestamp = null;

    /**
     * @return
     * @throws AuthFailureError
     */
    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        return HttpRequestNetManager.getInstance().getHeaders(timestamp);
    }

    public HttpJObjectRequest(int method, String url, String requestBody, Response.Listener listener, Response.ErrorListener errorListener) {
        super(method, url, requestBody, false, listener, errorListener);
    }
    public HttpJObjectRequest(int method, String url, String requestBody, boolean isform,Response.Listener listener, Response.ErrorListener errorListener) {
        super(method, url, requestBody, isform, listener, errorListener);
    }

    public HttpJObjectRequest(String url, String requestBody, boolean isform, Response.Listener listener, Response.ErrorListener errorListener) {
        super(Method.POST, url, requestBody, isform, listener, errorListener);
    }

    public HttpJObjectRequest(String url, String requestBody, Response.Listener listener, Response.ErrorListener errorListener) {
        super(Method.POST, url, requestBody, listener, errorListener);
    }

    public void setTimestamp(String times) {
        timestamp = times;
    }

    //map转换为json字符串
    public static String hashMapToJson(HashMap map) {
        String string = "{";
        for (Iterator it = map.entrySet().iterator(); it.hasNext(); ) {
            Map.Entry e = (Map.Entry) it.next();
            string += "'" + e.getKey() + "':";
            string += "'" + e.getValue() + "',";
        }
        string = string.substring(0, string.lastIndexOf(","));
        string += "}";
        return string;
    }


    @Override
    protected Response parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString =
                    new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            return Response.success(new JSONObject(jsonString),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }
}
